package com.jvxb.demo.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * MybatisPlus配置类
 * 1、实现分页
 * 2、实现插入/修改时自动修改时间（实体类上使用 @TableField(fill = FieldFill.INSERT/INSERT_UPDATE)）
 * 3、将返回的时间格式化为：yyyy-MM-dd HH:mm:ss
 */
@Configuration
@ConditionalOnClass(value = {PaginationInnerInterceptor.class})
@MapperScan("com.jvxb.demo.mapper")
public class MybatisPlusConfig implements MetaObjectHandler {

    @Bean
    public PaginationInnerInterceptor paginationInterceptor() {
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        return paginationInterceptor;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        this.setFieldValByName("createTime", date, metaObject);
        this.setFieldValByName("updateTime", date, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}